<?php

namespace App\Common\Components;

use App\Common\Exceptions\AppException;
use App\Common\JsonTrait;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class BaseController extends Controller
{
    use DispatchesJobs, ValidatesRequests,JsonTrait;

    /**
     * controller中执行报错需要回滚的action数组
     * @var array
     */
    public $transactionActions = [];

    public $apiErrMsg = [];

    public $apiData = [];

    protected $isPublic = false;


    public function __construct()
    {

    }

    /**
     * 前置action
     */

    public function preAction()
    {

    }

	public function callAction($method, $parameters)
	{
		if (method_exists($this,'preAction')) {
			call_user_func_array([$this, 'preAction'],$parameters);
		}
		// action设置了需要回滚
		if (method_exists($this, 'needTransaction') && $this->needTransaction($method)) {
			return DB::transaction(function() use ($method,$parameters) {
				return parent::callAction($method, $parameters);
			});
		}
		return parent::callAction($method, $parameters); // TODO: Change the autogenerated stub
	}


    /**
     * url参数验证
     *
     * @param array $rules
     * @param Request|null $request
     * @param array $messages
     * @param array $customAttributes
     *
     * @throws AppException
     */
    public function validate(array $rules, Request $request = null, array $messages = [], array $customAttributes = [])
    {
        if (!isset($request)) {
            $request = request();
        }
        $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);

        if ($validator->fails()) {
            throw new AppException($validator->errors()->first());
        }
    }


    /**
     * 需要回滚
     *
     * @param $action
     *
     * @return bool
     */
    private function needTransaction($action)
    {
        return in_array($action, $this->transactionActions) || in_array('*',
                $this->transactionActions) || $this->transactionActions == '*';
    }

    public function dataIntegrated($data, $flag)
    {
        if ($this->apiErrMsg) {
            return $this->successJson($this->apiErrMsg[0]);
        }

        if (0 == $data['status']) {
            $this->apiErrMsg[] = $data['json'];

            return;
        }

        $this->apiData[$flag] = $data['json'];
    }

    public function getIsPublic(): bool
	{
		return $this->isPublic;
	}


}
